<template>
  <div class="app-container">
    <el-card class="search-card">
      <!-- 搜索区域 -->
      <el-form :model="filterForm" class="filter-form">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="药剂名称/编号">
              <el-input v-model="filterForm.nameORCode" placeholder="请输入药剂名称或编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态">
              <el-select v-model="filterForm.status" placeholder="选择状态" clearable style="width: 100%">
                <el-option label="全部" value="" />
                <el-option v-for="item in statusOptions" :key="item.dictValue" :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="时间范围">
              <el-date-picker v-model="filterForm.dateRange" type="daterange" range-separator="至"
                start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="6" class="text-left">
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card class="mt-1">
      <!-- 操作按钮 -->
        <el-button type="primary" @click="handleAdd">
          新增药剂
        </el-button>
        <el-button :disabled="!selectedRows.length" @click="handleBatchDelete">
          批量删除
        </el-button>
      <!-- 化验药剂清单表格 -->
      <el-table :data="reagentList" border style="width: 100%" v-loading="loading"
        @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="reagentId" label="药剂编号" align="center" />
        <el-table-column prop="reagentName" label="药剂名称" align="center" />
        <el-table-column prop="specification" label="规格" align="center" />
        <el-table-column prop="stockQuantity" label="库存数量" align="center" />
        <el-table-column prop="manufacturer" label="生产厂家" align="center" />
        <el-table-column prop="expirationDate" label="有效期至" align="center" />
        <el-table-column prop="unit" label="单位" align="center" />
        <el-table-column prop="inboundTime" label="入库时间" align="center" width="180" />
        <el-table-column label="状态" align="center" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="220">
          <template #default="{ row }">
            <el-button type="text" size="small" @click="handleDetail(row.id)">详情</el-button>
            <el-button type="text" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" size="small" @click="handleDelete(row.id)" style="color: #f56c6c">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑化验药剂对话框 -->
    <el-dialog :title="formType === 'add' ? '新增化验药剂' : '编辑化验药剂'" v-model="formVisible" width="700px"
      :close-on-click-modal="false">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px" label-position="left">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="药剂编号" prop="reagentId">
              <el-input v-model="formData.reagentId" placeholder="输入药剂编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="药剂名称" prop="reagentName">
              <el-input v-model="formData.reagentName" placeholder="输入药剂名称" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生产厂家" prop="manufacturer">
              <el-input v-model="formData.manufacturer" placeholder="输入生产厂家" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="有效期至" prop="expirationDate">
              <el-date-picker v-model="formData.expirationDate" type="date" placeholder="选择有效期" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="规格" prop="specification">
              <el-input v-model="formData.specification" placeholder="输入规格" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-input v-model="formData.unit" placeholder="输入单位" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="库存数量" prop="stockQuantity">
              <el-input-number v-model="formData.stockQuantity" :min="0" :precision="2" controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预警库存数量" prop="warningStockQuantity">
              <el-input-number v-model="formData.warningStockQuantity" :min="0" :precision="2" controls-position="right"
                style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="入库时间" prop="inboundTime">
              <el-date-picker v-model="formData.inboundTime" type="date" placeholder="选择入库时间" value-format="YYYY-MM-DD"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-select v-model="formData.status" placeholder="选择状态" style="width: 100%">
                <el-option v-for="item in statusOptions" :key="+item.dictValue" :label="item.dictLabel"
                  :value="+item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 化验药剂详情对话框 -->
    <el-dialog title="化验药剂详情" v-model="detailVisible" width="800px" top="5vh" :close-on-click-modal="false">
      <el-descriptions border :column="2">
        <el-descriptions-item label="药剂编号">{{ currentDetail.reagentId }}</el-descriptions-item>
        <el-descriptions-item label="药剂名称">{{ currentDetail.reagentName }}</el-descriptions-item>
        <el-descriptions-item label="规格">{{ currentDetail.specification }}</el-descriptions-item>
        <el-descriptions-item label="库存数量">{{ currentDetail.stockQuantity }}</el-descriptions-item>
        <el-descriptions-item label="预警库存数量">{{ currentDetail.warningStockQuantity }}</el-descriptions-item>
        <el-descriptions-item label="单位">{{ currentDetail.unit }}</el-descriptions-item>
        <el-descriptions-item label="入库时间">{{ currentDetail.inboundTime }}</el-descriptions-item>
        <el-descriptions-item label="生产厂家">{{ currentDetail.manufacturer }}</el-descriptions-item>
        <el-descriptions-item label="有效期">{{ currentDetail.expirationDate }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentDetail.status)">
            {{ getStatusLabel(currentDetail.status) }}
          </el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getStatusList,
  listLaboratoryReagents,
  getLaboratoryReagents,
  addLaboratoryReagents,
  updateLaboratoryReagents,
  deleteLaboratoryReagents
} from '@/api/prod_operate/water/drug'

// 数据状态
const loading = ref(false)
const formVisible = ref(false)
const detailVisible = ref(false)
const formType = ref('add') // 'add' or 'edit'
const selectedRows = ref([])
const statusOptions = ref([])

// 筛选表单
const filterForm = reactive({
  nameORCode: '',
  status: '',
  dateRange: []
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 表单数据
const formData = reactive({
  id: null,
  reagentId: '',
  reagentName: '',
  specification: '',
  stockQuantity: 0,
  warningStockQuantity: 0,
  unit: '',
  inboundTime: '',
  status: ''
})

// 表单验证规则
const formRules = reactive({
  reagentId: [
    { required: true, message: '请输入药剂编号', trigger: 'blur' }
  ],
  reagentName: [
    { required: true, message: '请输入药剂名称', trigger: 'blur' }
  ],
  specification: [
    { required: true, message: '请输入规格', trigger: 'blur' }
  ],
  stockQuantity: [
    { required: true, message: '请输入库存数量', trigger: 'blur' }
  ],
  unit: [
    { required: true, message: '请输入单位', trigger: 'blur' }
  ],
  inboundTime: [
    { required: true, message: '请选择入库时间', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  expirationDate:[
    { required: true, message: '请输生产厂家', trigger: 'blur' }
  ],
  manufacturer:[
    { required: true, message: '请选择有效期', trigger: 'change' }
  ]
})

// 详情数据
const currentDetail = ref({})

// 化验药剂列表数据
const reagentList = ref([])

// 获取状态下拉列表
const fetchStatusList = async () => {
  try {
    const res = await getStatusList()
    statusOptions.value = res.data || []
  } catch (error) {
    console.error('获取状态下拉列表失败:', error)
    ElMessage.error('获取状态下拉列表失败')
  }
}

// 获取化验药剂列表
const fetchReagentList = async () => {
  try {
    loading.value = true
    const params = {
      nameORCode: filterForm.nameORCode,
      status: filterForm.status,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    if (filterForm.dateRange?.length === 2) {
      params.startTime = filterForm.dateRange[0]
      params.endTime = filterForm.dateRange[1]
    }

    const res = await listLaboratoryReagents(params)
    reagentList.value = res.rows || []
    pagination.total = res.total || 0
  } catch (error) {
    console.error('获取化验药剂列表失败:', error)
    ElMessage.error('获取化验药剂列表失败')
  } finally {
    loading.value = false
  }
}

// 获取化验药剂详情
const fetchReagentDetail = async (id) => {
  try {
    const res = await getLaboratoryReagents(id)
    currentDetail.value = res.data || {}
  } catch (error) {
    console.error('获取化验药剂详情失败:', error)
    ElMessage.error('获取化验药剂详情失败')
  }
}

// 查询处理
const handleQuery = () => {
  pagination.currentPage = 1
  fetchReagentList()
}

// 重置查询
const handleReset = () => {
  Object.assign(filterForm, {
    nameORCode: '',
    status: '',
    dateRange: []
  })
  handleQuery()
}

// 新增化验药剂
const handleAdd = () => {
  formType.value = 'add'
  Object.assign(formData, {
    id: null,
    reagentId: '',
    reagentName: '',
    specification: '',
    stockQuantity: 0,
    warningStockQuantity: 0,
    unit: '',
    inboundTime: '',
    status: ''
  })
  formVisible.value = true
}

// 编辑化验药剂
const handleEdit = (row) => {
  formType.value = 'edit'
  Object.assign(formData, row)
  formVisible.value = true
}

// 提交表单
const submitForm = async () => {
  try {
    if (formType.value === 'add') {
      await addLaboratoryReagents(formData)
      ElMessage.success('新增化验药剂成功')
    } else {
      await updateLaboratoryReagents(formData)
      ElMessage.success('修改化验药剂成功')
    }
    formVisible.value = false
    fetchReagentList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 查看详情
const handleDetail = async (id) => {
  await fetchReagentDetail(id)
  detailVisible.value = true
}

// 删除化验药剂
const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除该化验药剂吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteLaboratoryReagents(id)
      ElMessage.success('删除成功')
      fetchReagentList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  const ids = selectedRows.value.map(item => item.id).join(',')

  ElMessageBox.confirm(`确定要删除选中的${selectedRows.value.length}条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteLaboratoryReagents(ids)
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      fetchReagentList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }).catch(() => { })
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  fetchReagentList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchReagentList()
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '1': return 'success' // 正常
    case '2': return 'warning' // 库存不足
    case '3': return 'danger'  // 已过期
    default: return 'info'
  }
}

// 获取状态显示标签
const getStatusLabel = (status) => {
  const option = statusOptions.value.find(item => item.dictValue == status)
  return option ? option.dictLabel : status
}

// 初始化数据
onMounted(() => {
  fetchStatusList()
  fetchReagentList()
})
</script>

<style scoped>
.filter-form {
  margin-bottom: 20px;
}

.text-right {
  text-align: right;
}

.mb-2 {
  margin-bottom: 20px;
}

.highlight-text {
  color: #409EFF;
  font-weight: bold;
}


.search-card :deep(.el-form-item),
.search-card :deep(.el-form) {
  margin-bottom: 0px;
}
</style>